import { ExclamationCircleOutlined } from '@ant-design/icons';
import {
  Button,
  Col,
  Form,
  message,
  Modal,
  Radio,
  Row,
  Select,
  Tag,Tabs,Input,
} from 'antd';
import { useEffect, useRef, useState } from 'react';
import { history } from 'umi'
import { useDebounce } from '@/utils/utils'
import { statusTextMap, statusColorMap } from '@/pages/index/params'
import { TimeHeader } from '../index/components/index';
import OkrForm from './OkrForm';
import { queryUserName, insertOkr, selectOkr, updateOkrStatus } from '@/services/okr'
import styles from './index.less';

const { confirm } = Modal;
const { Option } = Select;
const { TabPane } = Tabs;
const { TextArea } = Input;

const NewOkr = (props) => {
  const okrId = props.location.query?.id;
  const type = props.location.query?.type;
  const reviewFlag = props.location.query?.reviewFlag;
  const departmentId = props.location.query?.departmentId;
  const category = props.location.query?.category;
  const [list, setList] = useState([]);
  const [isDetailFlag, setIsDetailFlag] = useState(okrId ? true : false); // 从列表进入，详情
  const [isEdit, setIsEdit] = useState(false); // isDetailFlag==true时才可以出现并改变
  const [jurisdiction, setJurisdiction] = useState('1');
  const [okrType, setOkrType] = useState(category); // okr类型
  const [saveTime, setSaveTime] = useState('2');
  const [status, setStatus] = useState('0');
  const [master, setMaster] = useState(); // id
  const [username, setUsername] = useState(); //name
  const [masterList, setMasterList] = useState([]);
  const [masterErr, setMasterErr] = useState(false);
  const [editYear, setEditYear] = useState();
  const [editQuarter, setEditQuarter] = useState();
  const [editTxt, setEditTxt] = useState();
  const [isLeader, setIsLeader] = useState(false);
  const [isOwner, setIsOwner] = useState(false);
  const [formkeys, setFormkeys] = useState();
  const [sinceScore, setSinceScore] = useState();
  const [score, setScore] = useState();
  const [owerId, setOwerId] = useState();
  const [klist, setKlist] = useState([]);
  const [count, setCount] = useState(0);
  const [activeKey, setActiveKey] = useState('1')
  const [cacheOkr, setCacheOkr] = useState({})
  const [commentList, setCommentList] = useState([
    {
      name: '王明',
      type: '已转阅',
      operate: '6',
      time: '2023-10-12 13:46:20',
      comment: ''
    },
    {
      name: '王凯华',
      type: '复盘审批通过',
      operate: '6',
      time: '2023-09-04 08:56:17',
      comment: '通过，依据复盘建议改正'
    },
    {
      name: '王伟',
      type: '复盘审批通过',
      operate: '6',
      time: '2023-09-03 16:30:27',
      comment: '通过，继续努力'
    },
    {
      name: '王伟',
      type: '复盘审批驳回',
      operate: '5',
      time: '2023-09-02 10:34:17',
      comment: '风险因素驳回，关联OKR未逾期，重新标注'
    },
    {
      name: '王凯华',
      type: '复盘审批驳回',
      operate: '5',
      time: '2023-08-29 17:22:27',
      comment: '未标明风险因素'
    },
    {
      name: '刘玥',
      operate: '4',
      type: '提交复盘',
      comment: '',
      time: '2023-08-20 13:28:28',
    },
    {
      name: '张一博',
      type: '已打分',
      operate: '3',
      time: '2023-05-17 15:28:32',
      score: '72',
      comment: ''
    },
    {
      name: '李维',
      type: '已打分',
      operate: '3',
      time: '2023-04-28 19:18:29',
      score: '86',
      comment: ''
    },
    {
      name: '刘玥',
      type: '已打分',
      operate: '3',
      time: '2023-04-20 15:07:09',
      score: '92',
      comment: ''
    },
    {
      name: '王佳',
      type: '审批通过',
      operate: '2',
      time: '2023-03-15 09:16:28',
      comment: '同意，可开展'
    },
    {
      name: '王伟',
      type: '审批通过',
      operate: '2',
      time: '2023-03-12 10:13:43',
      comment: '同意，可开展'
    },
    {
      name: '王佳',
      type: '审批驳回',
      operate: '1',
      time: '2023-03-10 16:34:20',
      comment: '相关KeyResult不够细致,应再细化一些，设置具象指标'
    },
    {
      name: '刘玥',
      type: '起草',
      operate: '1',
      time: '2023-03-04 18:14:20',
    }
  ])
  const [fpshow,setFpshow] = useState(false)

  const getOkrRef = useRef();
  const getTimeRef = useRef();
  const setTimeoutRef = useRef();
  const masterRef = useRef();
  const saveTimeRef = useRef();

  const [formOkr] = Form.useForm();
  const [formFp] = Form.useForm();
  useEffect(() => {
    if(okrId){
      getOkrDetail();
    }
  }, []);
  //   useEffect(() => {
  //     handleSetIntervalFun();
  //     return () => {
  //       clearTimeout(setTimeoutRef.current)
  //     }
  //   }, [isDetailFlag, isEdit])

  const handleSetIntervalFun = () => {
    let time = getTimeGap();
    clearTimeout(setTimeoutRef.current);
    if (
      (!isDetailFlag && !isEdit && type != '2') ||
      (isDetailFlag && isEdit && type != '2')
    ) {
      let timer = setTimeout(() => {
        saveData();
      }, time);
      setTimeoutRef.current = timer;
    }
  };

  const getTimeGap = () => {
    let time = 30 * 1000;
    const save_time = saveTimeRef?.current || '2';
    switch (save_time) {
      case '1':
        time = 10 * 1000;
        break;
      case '2':
        time = 30 * 1000;
        break;
      case '3':
        time = 5 * 60 * 1000;
        break;
      case '4':
        time = 10 * 60 * 1000;
        break;
      default:
        time = 30 * 1000;
        break;
    }
    return time;
  };
  const getOkrDetail = async () => {
    const result = await selectOkr({ okrid: okrId });
    const res = result.data.okr;
    setCacheOkr(res?.objectiveList)
    setList(res?.objectiveList);
    setOkrType(res?.type);
    setCount(1)
    setEditYear(res.year);
    setEditQuarter(res.quarter);
    setMaster(res?.master);
    setUsername(res?.username)
    masterRef.current = res?.master;
    setStatus(res?.status);
    setIsLeader(res?.leader == '1');// 是否是领导
    setIsOwner(res?.oneself == '1');// 是否登录用户
    setIsEdit(okrId && res.jurisdiction === '1' ? true : false)
    if (Number(res.status) === 3) { // 评分审批中
       setJurisdiction(res?.leader)
    } else if(Number(res.status) < 3){
       setJurisdiction(res?.oneself)
    } else {
       setJurisdiction('0')
    }
    if ( res.status != '1' && (res.jurisdiction == '1' || res.whetherleader == '1')) {
      initWebsocket();
    }
  };
  const validateData = (list) => {
    let errCount = 0;
    list.forEach((item, index) => {
      if (item.okrnameErr || item.weightErr || !item.oname || !item.oweight) {
        errCount++;
      }
      if (item.okrDetailPoList.length > 0) {
        item.okrDetailPoList.forEach((val, num) => {
          if (
            val.krnameErr ||
            !val.content ||
            !val.path ||
            !val.confidence ||
            val.krpathErr ||
            !val.weight ||
            val.krWeightErr ||
            val.krConfidenceErr
          ) {
            errCount++;
          }
        });
      }
    });
    return errCount;
  };
  const saveData = () => {
    // 获取所有KR数据 list
    const allOkrList = getOkrRef?.current?.allOkrList || [];
    const year = getTimeRef?.current?.year || (isDetailFlag ? editYear : newYear);
    const quarter = getTimeRef?.current?.quarter || (isDetailFlag ? editQuarter : newQuarter) || '0';
    let newOkrList = getParamsList(allOkrList);
    const params = {
      category: okrType,
      owerId: departmentId || '',
      year,
      quarter,
      status,
      score: newOkrList.reduce(
        (total, cur) => total + ((cur.oscore * cur.oweight) / 100 || 0),
        0,
      ),
      sinceScore: newOkrList.reduce(
        (total, cur) => total + ((cur.osinceScore * cur.oweight) / 100 || 0),
        0,
      ),
      master: masterRef.current ? masterRef.current : userName,
      okrODetailVoList: newOkrList,
      id: okrId ? okrId : '',
    };
    onSubmit(params)
  };
  const onSubmit = (tip) => {
    formOkr.validateFields().then((data) => {
      const listN = klist.map((k) => {
        return {
          id:data[`id${k}`] || '',
          oname: data[`oname${k}`],
          oweight: data[`oweight${k}`],
          oprogress: data[`oprogress${k}`] || 0,
          oscore: data[`oscore${k}`] || 0, // 自评分
          ofinalscore: data[`ofinalscore${k}`] || 0, //最终得分
          okrDetailPoList: data[`okrDetailPoList${k}`],
        };
      });
      const sum = listN.length > 0  ? judgeWeight(listN) : 0;
      const krListFlag = listN.length > 0 ? judgeOkrListIsEmpty(listN) : true;
      if (sum != 100 && status == '0') {
        message.error('所有O的权重总和需等于100，请检查，重新填写权重！');
      }  else if(!krListFlag) {
        message.error('每个O至少需要有一个KR，请检查并填写');
      } else {
        const filterArr = judgeWeight2(listN);
        if (filterArr.length > 0) {
          confirm({
            title: '部分KR的权重超过50，确定要继续保存吗？',
            icon: <ExclamationCircleOutlined />,
            content: '',
            onOk() {
              transData(listN, tip)
            },
            onCancel() {},
          });
        } else {
          transData(listN, tip)
        }
      }
    });
  };
  const getParamsList = (list) => {
    let newList = list.map((item) => {
      return {
        ...item,
        osinceScore: status == 4 ? item.okrDetailPoList ?.reduce(function (prev, cur) {
                  return prev + ((cur.sinceScore * cur.weight) / 100 || 0);
                }, 0).toFixed(3) : item.osinceScore,
        oscore: status == 2 || status == 3 ? item.okrDetailPoList ?.reduce(function (prev, cur) {
                  return prev + ((cur.krscore * cur.krweight) / 100 || 0);
                }, 0).toFixed(3) : item.oscore,
        oprogress: item.okrDetailPoList ?.reduce(function (prev, cur) {
            return prev + ((cur.progress * cur.weight) / 100 || 0);
          }, 0).toFixed(0),
        okrDetailPoList: item.okrDetailPoList?.map((val) => {
          return { ...val, type: '1' };
        }),
      };
    });
    return newList;
  };
  const transData = (listN, tip) => {
    const { year, quarter } = getTimeRef.current;
    let params = {
      year,
      quarter,
      master: masterRef.current,
      username,
      list: listN,
      type: category,
      departmentId,
      okrId,
      status: status || '0',
    }
    if(tip){
      updateOkrStatus(params).then((res)=>{
        history.push('/index')
      })
    }else {
      insertOkr(params).then((res)=>{
        history.push('/index')
      })
    }
  }
  const judgeWeight = (arr) => {
    const newArr = arr.map((item) => item.oweight);
    const sum = newArr.reduce((prev, curr) => {
      return Number(prev) + Number(curr);
    });
    return sum;
  };
  const judgeWeight2 = (arr) => {
    const newArr = arr.filter((item) => Number(item.oweight) > 50);
    return newArr;
  };
  const judgeOkrListIsEmpty = (arr) => {
    const flagArr = arr.every((item) => {
      let flag = true;
      if((item.okrDetailPoList instanceof Array) && item.okrDetailPoList.length == 0){
        flag = false;
      } else if(!item.okrDetailPoList){
        flag = false;
      } else {
        flag = true
      }
      return flag;
    });
    return flagArr;
  }

  const saveDateFun = async (params) => {
    let res = await save(params);
    // router.push('/okr')
    // if(status === '0' && !isDetailFlag && !isEdit) {
    // }else {
    //   router.push('/okr')
    // }
  };

  const saveDataEmit = (allOkrList, tip) => {
    const { year, quarter } = getTimeRef.current;
    let newOkrList = getParamsList(allOkrList);
    const params = {
      category: okrType,
      owerId: departmentId || '',
      year,
      quarter,
      status,
      score: newOkrList
        .reduce(
          (total, cur) => total + ((cur.oscore * cur.oweight) / 100 || 0),
          0,
        )
        .toFixed(3),
      sinceScore: newOkrList
        .reduce(
          (total, cur) => total + ((cur.osinceScore * cur.oweight) / 100 || 0),
          0,
        )
        .toFixed(3),
      master: master ? master : userName,
      okrODetailVoList: newOkrList,
      id: okrId ? okrId : '',
    };
    saveDateFun(params)
      .then(() => {
        if (tip === '3') {
          submitapproval({ id: okrId }).then(() => {
            router.push('/okr');
          });
        } else {
          if (reviewFlag == '1' && isLeader) {
            location.reload();
          } else {
            router.push('/okr');
          }
        }
      })
      .catch((err) => {
        message.error(err?.msg || '保存失败');
      });
  };
  const onBack = () => {
    if (status !== '0') {
      updateComment();
    }
  };
  const changeTime = (value) => {
    setSaveTime(value);
    saveTimeRef.current = value;
  };
  const handleMaster = (value) => {
    const list = value.split('-');
    setMaster(list[0]);
    setUsername(list[1])
    masterRef.current = list[0];
  };
  const updateComment = async () => {
    const res = await detail({ id: okrId });
    setOkrLogPoList(res?.okrLogPoList);
    setOkrCommentList(res?.okrCommentList);
    setOkrFlowPoList(res?.okrFlowPoList);
  };
  const goApproval = (tip) => {
    setSuggestStatus(tip);
    setSuggestVisible(true);
  };
  const onClose = () => { history.goBack(); };
  const updateList = (ks) => {
    setKlist(ks);
  };

  const searchVal = (value) => {
    initDebounce(value)
  }
  const initDebounce = useDebounce((val) => {
    if(val){
      queryUserName({name: val}).then((result)=>{
        if(result.code == 200) {
          const list = result.data.user || [];
          setMasterList(list)
        }
      })
    }
  }, 2000)
  const onChangeTab = (key) => {
    setActiveKey(key)
  }
  const renderColor = (num) => {
    let color = 'red'
    switch(num){
      case '1':  color = 'green';break;
      default: color = 'green'; break;
    }
    return color;
  }
  const handleOk = () => {
    setFpshow(false)
  }
  const handleCancel = () => {

  }

  const editPermission = jurisdiction == '1' && isDetailFlag && !isEdit && (status == '0' || status == '2' || (status == '3' && isLeader)); //编辑权限(isEdit)
  const statusFlag1 = status == '0' && isEdit;
  const statusFlag2 = status == '1' && isOwner; //个人，展示评审退回
  const statusFlag2_1 = status == '1' && isLeader; //领导，展示通过
  const statusFlag3 = status == '2' && isEdit; // 可以评分了
  const statusFlag4 = isLeader && status == '3' && isEdit; // 评分审批中（领导编辑）
  const statusFlag5 = status == '4' && isOwner; // 开始复盘
  const statusFlag6 = status == '5' && isLeader; // 复盘审批
  const options = [
    { label: '关联目标逾期', value: '1' },
    { label: '关联比率调整', value: '2' },
    { label: '信心指数调整', value: '3' },
    { label: 'OKR人员变动', value: '4' },
  ]

  return (
    <>
      {/* <div className={styles.okr_small_title} style={{ width: '80px', cursor: 'pointer' }} onClick={() => { history.push('/index') }}>
        首页/OKR
      </div> */}
      <Tabs
        onChange={onChangeTab}
        activeKey={activeKey}
        type="card"
      >
        <TabPane tab='制定OKR' key='1'>
        <div className={styles.okr_detail_wrap}>
        <div
          className={styles.okr_detail_wrap_left}
          style={{ backgroundColor: '#fff', padding: '10px 20px' }}
        >
          <Row>
            <Col span={24} className={styles.okr_type_wrap}>
              <span className={styles.okr_outer_label}>类型</span>
              <Radio value={okrType} checked={true}>
                {okrType === '2' ? '部门OKR' : '个人OKR'}
              </Radio>
              {isDetailFlag && (
                <Tag style={{ height: '24px' }} color={statusColorMap.get(status+'')}>
                  {statusTextMap.get(status+'')}
                </Tag>
              )}
              {((!isDetailFlag && !isEdit && type != '2') ||
                (isEdit && isDetailFlag && type != '2')) && (
                <div className={styles.okr_save_wrap}>
                  <span>自动保存：</span>
                  <Select
                    value={saveTime}
                    style={{ width: 100 }}
                    onChange={changeTime}
                  >
                    <Option value="1">10秒</Option>
                    <Option value="2">30秒</Option>
                    <Option value="3">5分钟</Option>
                    <Option value="4">10分钟</Option>
                  </Select>
                </div>
              )}
            </Col>
            <Col span={24} className={styles.okr_type_wrap}>
              <span className={styles.okr_outer_label}>周期</span>
              <TimeHeader
                okrType={okrType}
                pageSource={'okr-detail'}
                updateList={() => {}}
                isDetailFlag={isDetailFlag}
                ref={getTimeRef}
                editYear={editYear}
                editQuarter={editQuarter}
                departmentId={departmentId}
              />
            </Col>
            <Col span={24} className={styles.okr_type_wrap}>
              <span className={styles.okr_outer_label}>负责人</span>
              <Select
                disabled={
                  (isDetailFlag && !isEdit) ||
                  type == '2' ||
                  status == '2' ||
                  status == '3' ||
                  status == '4' ||
                  status == '5' ||
                  status == '6' ||
                  status == '7'
                }
                showSearch
                value={username}
                onSearch={searchVal}
                placeholder="输入用户名或姓名进行搜索"
                getPopupContainer={(triggerNode) => triggerNode.parentNode}
                notFoundContent={null}
                onChange={handleMaster}
                style={{ width: '250px' }}
              >
                {masterList.map((user) => (
                  <Option
                    value={`${user.id}-${user.username}`}
                    key={user.id}
                  >{`${user.username}`}</Option>
                ))}
              </Select>
            </Col>
            {masterErr && !master && (
              <Col span={24} style={{ paddingLeft: '60px', color: 'red' }}>
                负责人不能为空
              </Col>
            )}
          </Row>
          <Row style={{ marginTop: 20 }} className={styles.okr_form_wrap}>
            <OkrForm
              form={formOkr}
              updateList={updateList}
              isEdit={isEdit}
              isDetailFlag={isDetailFlag}
              status={status}
              jurisdiction={jurisdiction}
              count={count}
              olist={list}
              isLeader={isLeader}
              okrId={okrId}
            ></OkrForm>
          </Row>
            <div style={{ display: 'flex', justifyContent: 'center' }}>
                {editPermission && (
                  <Button
                    type="primary"
                    style={{ marginRight: '10px' }}
                    onClick={() => {
                      setIsEdit(true);
                    }}
                  >
                    {Number(status) == 3 ? '进行最终评分' : '编辑'}
                  </Button>
                )}

                {statusFlag1 && (<><Button type="primary" style={{ marginRight: '10px' }} onClick={() => onSubmit('1')}>提交评审</Button></>)}
                {statusFlag2 && (<> <Button type="primary" style={{ marginRight: '10px' }} onClick={()=>onSubmit('0')}>评审撤回</Button></>)}
                {statusFlag2_1 && (<> <Button type="primary" style={{ marginRight: '10px' }} onClick={onSubmit}>通过</Button></>)}
                {statusFlag3 && (<><Button type="primary" style={{ marginRight: '10px' }} onClick={() => onSubmit('1')}>提交自评分</Button></>)}
                {statusFlag4 && (<><Button type="primary" style={{ marginRight: '10px' }} onClick={onSubmit}>评分通过</Button></>)}
                {statusFlag5 && (<> <Button type="primary" style={{ marginRight: '10px' }} onClick={() =>{ setFpshow(true) }}>复盘</Button></>)}
                {statusFlag6 && (<> <Button type="primary" style={{ marginRight: '10px' }} onClick={onSubmit}>通过</Button></>)}
                {(statusFlag2_1 || statusFlag4 || statusFlag6) && (<Button type="" style={{ marginRight: '10px' }} onClick={onClose}>驳回</Button>)}
                {(status == '0' || status == '2') && (<Button type="primary" style={{ marginRight: '10px' }} onClick={()=>onSubmit('')}>保存</Button> )}
                {status == '6' && <Button type="" style={{ marginRight: '10px' }} disabled >完结</Button>}
                <Button type="" style={{ marginRight: '10px' }} onClick={onClose}>返回</Button>
                </div>
              </div>
              {editTxt !== '连接成功' && status !== '0' && (
                <div className="fix-right-editing">{editTxt}...</div>
              )}
            </div>
        </TabPane>
        <TabPane tab='流程图' key='2'>
           <div style={{padding: '10px 200px',position: 'relative'}}>
             <div className={styles.trigle}></div>
              {commentList.map((item)=>(<div className={styles.comment_wrap}>
                 <div className={styles.comment_user}>{item.name}<span className={styles.comment_time}>{item.time}</span></div>
                 <div className={styles.comment_type}>{item.type}</div>
                 <div className={styles.comment_spot}>
                    <div className={styles.inner_spot}></div>
                 </div>
                 {item.comment && <div className={styles.comment_detail}>{item.comment}</div>}

              </div>))}
           </div> 
        </TabPane>
      </Tabs>
      {fpshow && <Modal title="开始复盘" width={680} open={fpshow}  onCancel={handleCancel}
         footer={<>
           <Button type="primary" onOk={handleOk}> 复盘审批</Button>
           <Button type="" onClick={()=>{ setFpshow(false) }}>返回</Button>
         </>}
       >
          <div className={styles.fp_form}>
          <Form autoComplete="off" form={formFp} layout="vertical">
              <div style={{ position: 'relative' }}>
              <Form.Item
                  name={`fpAward`}
                  label="OKR成果"
                >
                  <TextArea></TextArea>
                </Form.Item>
                <Form.Item
                  name={`fpQuestion`}
                  label="隐藏问题"
                >
                  <TextArea></TextArea>
                </Form.Item>
                <Form.Item
                  name={`fpRisk`}
                  label="逾期风险因素"
                >
                  <Select
                    mode="multiple"
                    allowClear
                    style={{
                      width: '100%',
                    }}
                    placeholder="风险因素"
                    options={options}
                  />
                </Form.Item>
                <Form.Item
                  name={`fpLook`}
                  label="自我审视"
                >
                  <TextArea></TextArea>
                </Form.Item>
                <Form.Item
                  name={`fpExperise`}
                  label="总结经验"
                >
                  <TextArea></TextArea>
                </Form.Item>
              </div>
           </Form>
          </div>
        </Modal>}
    </>
  );
};
export default NewOkr;
